package com.emser.unc.database.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.emser.unc.database.MySQLiteHelper;

public class VersionDataSource {
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	
	public VersionDataSource(Context context){
		dbHelper = new MySQLiteHelper(context);
	}
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}
	
	public void setVersion(String table, Long numVersion){
			String[] whereArgs = new String[] { table };
			database.delete(MySQLiteHelper.TABLE_VERSION, "table_name = ?", whereArgs);
			ContentValues values = new ContentValues();
			values.put("table_name", table);
			values.put("last_version", numVersion);
			database.insert(MySQLiteHelper.TABLE_VERSION, null, values);
	}
	
	public Long getVersion(String table) {
		try {
			String query = "SELECT * FROM " + MySQLiteHelper.TABLE_VERSION +" WHERE table_name = ?";
			String[] whereArgs = new String[] { table };
			Cursor cursor = database.rawQuery(query, whereArgs);
			cursor.moveToFirst();
			Long version = cursorToVersion(cursor);
			cursor.close();
			return version;
		} catch (Exception e) {
			return null;
		}
	}
	
	private Long cursorToVersion(Cursor cursor) {
		return cursor.getLong(2);
	}
	

}
